package util;

import java.util.Hashtable;
import java.util.List;

import model.UserProfile;

public class CommonCalls {
	static public List<model.ProfileFieldDefinition> getFieldDefinitions(){
		return HibernateUtil.list("from ProfileFieldDefinition");	
	}
	static public Hashtable<Integer, model.UserProfile> getUserInformation(String id){
		Hashtable<Integer, model.UserProfile> userInfo = new Hashtable<Integer, UserProfile>();
		List<model.ProfileFieldDefinition> fields = CommonCalls.getFieldDefinitions();
		for(int a=0;a<fields.size();a++){			
			userInfo.put(Integer.valueOf(fields.get(a).getId()), CommonCalls.getSingleUserInformation(id, String.valueOf(fields.get(a).getId())));
		}
		return userInfo;
	}
	static public model.UserProfile getSingleUserInformation(String userId, String fieldDefId){
		String query = "from UserProfile as up where up.userId = '"+userId+"' and up.profileFieldDefinitionId = '"+fieldDefId+"'";
		List<model.UserProfile> info = HibernateUtil.list(query);
		if(info.size() > 0)
			return info.get(0);
		return createSingleUserInformation(userId,fieldDefId);
	}
	static public model.UserProfile createSingleUserInformation(String userId, String fieldDefId){
		UserProfile up = new UserProfile();
		up.setPrivate(true);
		up.setUserId(Integer.parseInt(userId));
		up.setProfileFieldDefinitionId(Integer.parseInt(fieldDefId));
		up.setInputValue(getDefaultValue(fieldDefId));
		HibernateUtil.insert(up);
		return up;
	}
	static public model.UserProfile updateSingleUserInformation(String userId, String fieldDefId, String value){
		UserProfile up = CommonCalls.getSingleUserInformation(userId, fieldDefId);
		up.setInputValue(value);
		HibernateUtil.update(up);
		return up;
	}
	static public model.UserProfile updateSingleUserInformation(String userId, String fieldDefId, String value, Boolean privacy){
		UserProfile up = CommonCalls.getSingleUserInformation(userId, fieldDefId);
		up.setInputValue(value);
		up.setPrivate(privacy);
		HibernateUtil.update(up);
		return up;
	}
	static public String getDefaultValue(String fieldDefId){
		String query = "from ProfileFieldDefinition as pfd where pfd.id = '" +fieldDefId+"'";
		List<model.ProfileFieldDefinition> list = HibernateUtil.list(query);
		if(list.size()<=0)
			return "";
		else{
			return list.get(0).getDefaultValue();
		}
	}
	static public model.ProfileFieldDefinition getSingleFieldDefinition(String fieldDefId){
		String query="from ProfileFieldDefinition where id='"+fieldDefId+"'";
		List<model.ProfileFieldDefinition> l = HibernateUtil.list(query);
		if (l.size() == 0)
			return null;
		else return l.get(0);
	}
	static public String getSeperator(){
		return "\\|";
	}
}